﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAO;

namespace TAM_SPORT
{
    public partial class CustomerList : Form
    {
        private PurchaseDao dao = null;
        DataTable table = null;
        private int rowNumber = 0;
        public CustomerList()
        {
            
            InitializeComponent();
            dao = new PurchaseDao();
            table = new DataTable();

            dtgCustomers.ColumnHeadersDefaultCellStyle.BackColor = Color.Khaki;
            dtgCustomers.GridColor = Color.Khaki;
            dtgCustomers.EnableHeadersVisualStyles = false;
            if ("0".Equals(SqlHelper.readConfigFile("Delete Many Rows")))
            {
                clInactive.Visible = true;
                clCheckAll.Visible = false;
                btnDeleteAll.Visible = false;
            }
            else
            {
                clInactive.Visible = false;
                clCheckAll.Visible = true;
                btnDeleteAll.Visible = true;
            }
            init("", "A", false);
        }


        public CustomerList(string searchText)
        {

            InitializeComponent();
            txtName.Text = searchText;
            dao = new PurchaseDao();
            table = new DataTable();

            dtgCustomers.ColumnHeadersDefaultCellStyle.BackColor = Color.Khaki;
            dtgCustomers.GridColor = Color.Khaki;
            dtgCustomers.EnableHeadersVisualStyles = false;
            if ("0".Equals(SqlHelper.readConfigFile("Delete Many Rows")))
            {
                clInactive.Visible = true;
                clCheckAll.Visible = false;
                btnDeleteAll.Visible = false;
            }
            else
            {
                clInactive.Visible = false;
                clCheckAll.Visible = true;
                btnDeleteAll.Visible = true;
            }
            init(searchText, "A", false);
        }

        private void CustomerList_Load(object sender, EventArgs e)
        {
            
        }

        private void init(string name, string active, bool fifo)
        {
            if (rowNumber == 0)
            {
                dtgCustomers.Rows.Clear();
            }
            
            if (fifo == false)
            {
                table = dao.getCustommer(name, active);
            }
            else
            {
                table = dao.getCustommerFifo(name, active);

            }
            if (table != null && table.Rows.Count > 0)
            {
                
                DataRow row = null;
                int expireCount = 0;
                int nearExpireCount = 0;
                foreach (DataRow rowtem in table.Rows)
                {
                    if (string.IsNullOrEmpty(rowtem["DAY_ONLY"].ToString()) || "F".Equals(rowtem["DAY_ONLY"].ToString()))
                    {

                        if (rowtem["EXPIRATION_DATE"].GetType().FullName == "System.DBNull" || DateTime.Parse(rowtem["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(3))
                        {
                            
                              
                                expireCount++;
                        }
                        if (rowtem["EXPIRATION_DATE"].GetType().FullName != "System.DBNull" && System.DateTime.Now.AddDays(3) < DateTime.Parse(rowtem["EXPIRATION_DATE"].ToString()) && DateTime.Parse(rowtem["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(5))
                        {
                            nearExpireCount++;
                        }
                    }
                }
                lbResult.Text = UserConstant.RESULT_1 + table.Rows.Count.ToString() + UserConstant.RESULT_2 + " ( " + expireCount + " đỏ -  " + nearExpireCount + " vàng )";
                for (int j = rowNumber * 100; j < (rowNumber + 1) * 100; j++)
                // foreach(DataRow row in table.Rows)
                {
                    if (j >= table.Rows.Count)
                    {
                        break;
                    }
                    row = table.Rows[j];
                    int i = dtgCustomers.Rows.Add();
                    dtgCustomers.Rows[i].Cells[0].Value = row["ID"].ToString();
                    dtgCustomers.Rows[i].Cells[1].Value = i + 1;
                    dtgCustomers.Rows[i].Cells[2] = row["PICTURE"] == null ? null : loadImage(row["PICTURE"].ToString());
                    dtgCustomers.Rows[i].Cells[3].Value = row["NAME"] == null ? "" : row["NAME"].ToString();
                    dtgCustomers.Rows[i].Cells[4].Value = row["NOTE"] == null? "" : row["NOTE"].ToString();
                    dtgCustomers.Rows[i].Cells[5].Value = (row["PURCHASE_DATE"].GetType().FullName == "System.DBNull") ? "" : DateTime.Parse(row["PURCHASE_DATE"].ToString()).ToString("dd/MM/yy");
                    dtgCustomers.Rows[i].Cells[6].Value = (row["EXPIRATION_DATE"].GetType().FullName == "System.DBNull") ? "" : DateTime.Parse(row["EXPIRATION_DATE"].ToString()).ToString("dd/MM/yy");
                    if (row["DAY_ONLY"] != null && "T".Equals(row["DAY_ONLY"].ToString()))
                    {
                        dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Violet;
                    }
                    else
                    {
                        if (row["EXPIRATION_DATE"].GetType().FullName == "System.DBNull" || DateTime.Parse(row["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(3))
                        {
                            if (row["DAY_ONLY"] != null && "T".Equals(row["DAY_ONLY"].ToString()))
                            {
                                dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Violet;
                            }
                            else
                            {
                                dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                            }
                        }
                        if (row["EXPIRATION_DATE"].GetType().FullName != "System.DBNull" && System.DateTime.Now.AddDays(3) < DateTime.Parse(row["EXPIRATION_DATE"].ToString()) && DateTime.Parse(row["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(5))
                        {
                            dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                        }
                    }
                    if (j == table.Rows.Count - 1)
                    {
                        break;
                    }
                }
               
            }
            else
            {
                lbResult.Text = UserConstant.RESULT_3; 
            }
        }

        private Image resizeImage(Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }

        private DataGridViewImageCell loadImage(string url)
        {
            try
            {
                Image image = Image.FromFile(url);
                DataGridViewImageCell imageCell = new DataGridViewImageCell();
                Image imagedis = resizeImage(image, new Size(150, 150));
                imageCell.Value = imagedis;
                image.Dispose();
                return imageCell;
            }
            catch
            {
                return new DataGridViewImageCell();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string name = txtName.Text.Trim();
            string active = "A";
            bool fifo = false;
            if (cbxInactive.Checked)
            {
                active = null;
            }
            if (cbxFifo.Checked)
            {
                fifo = true;
            }
            dtgCustomers.Rows.Clear();
            rowNumber = 0;
            init(name, active, fifo);
        }

        private void dtgCustomers_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                string active = "A";
                if (cbxInactive.Checked == true)
                {
                    active = null;
                }
                bool fifo = cbxFifo.Checked;
                string name = dtgCustomers.Rows[e.RowIndex].Cells[3].Value.ToString();

                if (e.RowIndex >= 0 && e.ColumnIndex == 7)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());

                    Confirm f = new Confirm(UserConstant.CONFIRM_1 + name + UserConstant.CONFIRM_2);
                    f.ShowDialog();
                    if (f.IsAccept)
                    {
                        if (dao.deleteCustomer(id))
                        {
                            Result r = new Result(UserConstant.SAVE_SUCCESSFUL);
                            r.ShowDialog();
                            r.Dispose();
                            rowNumber = 0;
                            init(txtName.Text.Trim(), active, cbxFifo.Checked);
                        }
                        else
                        {
                            Error r = new Error(UserConstant.SAVE_FAIL);
                            r.ShowDialog();
                            r.Dispose();
                            rowNumber = 0;
                            init(txtName.Text.Trim(), active, cbxFifo.Checked);
                        }
                    }
                    f.Dispose();

                    /*
                    if (MessageBox.Show("Bạn có chắc hoc viên " + name + " đã nghỉ tập ?", "Warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        if (dao.deleteCustomer(id))
                        {
                            MessageBox.Show("Lưu thành công");
                            dtgCustomers.Rows.Clear();
                            rowNumber = 0;
                            init(txtName.Text.Trim(), active, fifo);
                        }
                    }
                     * */
                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 1)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    dao.remindOrUnremindCustomer(id);
                    init(txtName.Text.Trim(), active, fifo);
                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 2)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    Purchase p = new Purchase(id);
                    p.ShowDialog();
                    dtgCustomers.Rows.Clear();
                    rowNumber = 0;
                    init(txtName.Text.Trim(), active, fifo);
                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 3)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    UpdateCustomer p = new UpdateCustomer(id);
                    p.ShowDialog();
                    dtgCustomers.Rows.Clear();
                    rowNumber = 0;
                    init(txtName.Text.Trim(), active, fifo);

                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 6)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    CustomerRemindHist p = new CustomerRemindHist(id);
                    p.ShowDialog();
                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 4)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    CustomerDetail p = new CustomerDetail(id);
                    p.ShowDialog();
                }
                else if (e.RowIndex >= 0 && e.ColumnIndex == 5)
                {
                    int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                    PurchaseDay p = new PurchaseDay(id);
                    p.ShowDialog();
                    dtgCustomers.Rows.Clear();
                    rowNumber = 0;
                    init(txtName.Text.Trim(), active, fifo);
                }
            }
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            /*
            dtgCustomers.Rows.Clear();
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    if (row["NAME"].ToString().ToUpper().Contains(txtName.Text.Trim().ToUpper()))
                    {
                        int i = dtgCustomers.Rows.Add();
                        dtgCustomers.Rows[i].Cells[0].Value = row["ID"].ToString();
                        dtgCustomers.Rows[i].Cells[1].Value = i + 1;
                        dtgCustomers.Rows[i].Cells[2] = loadImage(row["PICTURE"].ToString());
                        dtgCustomers.Rows[i].Cells[3].Value = row["NAME"].ToString();
                        dtgCustomers.Rows[i].Cells[4].Value = row["NOTE"].ToString();
                        dtgCustomers.Rows[i].Cells[5].Value = DateTime.Parse(row["PURCHASE_DATE"].ToString()).ToShortDateString();
                        dtgCustomers.Rows[i].Cells[6].Value = DateTime.Parse(row["EXPIRATION_DATE"].ToString()).ToShortDateString();
                        if (DateTime.Parse(row["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(3))
                        {
                            if (row["DAY_ONLY"] != null && "T".Equals(row["DAY_ONLY"].ToString()))
                            {
                                dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Violet;
                            }
                            else
                            {
                                dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                            }
                        }
                        if (System.DateTime.Now.AddDays(3) < DateTime.Parse(row["EXPIRATION_DATE"].ToString()) && DateTime.Parse(row["EXPIRATION_DATE"].ToString()) <= System.DateTime.Now.AddDays(5))
                        {
                            dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                        }
                    }
                }
            }
             */
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string active = "A";
            if (cbxInactive.Checked)
            {
                active = null;
            }
            bool fifo = cbxFifo.Checked;
            Purchase p = new Purchase(true);
            p.ShowDialog();
            dtgCustomers.Rows.Clear();
            rowNumber = 0;
            init(txtName.Text.Trim(), active, fifo);
        }

        private void dtgCustomers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string active = "A";
            if (cbxInactive.Checked == true)
            {
                active = null;
            }

            string name = "";
            if (e.RowIndex >= 0)
            {
                dtgCustomers.Rows[e.RowIndex].Cells[3].Value.ToString();
            }

            if (e.RowIndex >= 0 && e.ColumnIndex == 7)
            {
                int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[0].Value.ToString());
                Confirm f = new Confirm(UserConstant.CONFIRM_1 + name + UserConstant.CONFIRM_2);
                f.ShowDialog();
                if (f.IsAccept)
                {
                    if (dao.deleteCustomer(id))
                    {
                        Result r = new Result(UserConstant.SAVE_SUCCESSFUL);
                        r.ShowDialog();
                        r.Dispose();
                        rowNumber = 0;                        
                        init(txtName.Text.Trim(), active, cbxFifo.Checked);                        
                    }
                    else
                    {
                        Error r = new Error(UserConstant.SAVE_FAIL);
                        r.ShowDialog();
                        r.Dispose();
                        rowNumber = 0;
                        init(txtName.Text.Trim(), active, cbxFifo.Checked);                        
                    }
                }
                f.Dispose();

                /*
                if (MessageBox.Show("Bạn có chắc hoc viên " + name + " đã nghỉ tập ?", "Warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    if (dao.deleteCustomer(id))
                    {
                        MessageBox.Show("Lưu thành công");

                        dtgCustomers.Rows.Clear();
                        rowNumber = 0;
                        init(txtName.Text.Trim(), active, cbxFifo.Checked);
                    }
                }
                  */
            }
        }

        private void cbxInactive_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void dtgCustomers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnAddCustomerDay_Click(object sender, EventArgs e)
        {
            string active = "A";
            if (cbxInactive.Checked)
            {
                active = null;
            }
            bool fifo = cbxFifo.Checked;
            PurchaseDay p = new PurchaseDay(true);
            p.ShowDialog();
            dtgCustomers.Rows.Clear();
            rowNumber = 0;
            init(txtName.Text.Trim(), active, fifo);
        }

        private void dtgCustomers_Scroll(object sender, ScrollEventArgs e)
        {
            string name = txtName.Text.Trim();
            string active = "A";
            bool fifo = false;
            if (cbxInactive.Checked)
            {
                active = null;
            }
            if (cbxFifo.Checked)
            {
                fifo = true;
            }           
            if (dtgCustomers.FirstDisplayedScrollingRowIndex +5>= (rowNumber + 1) * 100)
            {
                rowNumber++;
                init(name, active, fifo); 
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            Export();
        }

        private void Export()
        {
            saveFile.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            string fileName = "";

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                fileName = saveFile.FileName;
            }
            ExcelManager excelManager = new ExcelManager();
            if (!string.IsNullOrEmpty(fileName))
            {
                excelManager.ExportCustomers(txtName.Text.Trim(),fileName);
            }
            saveFile.FileName = null;
        }

        private void btnDeleteAll_Click(object sender, EventArgs e)
        {
            List<int> ListId = new List<int>();
            int id = 0;
            for (int i = 0; i < dtgCustomers.Rows.Count; i++ )
            {
                if (dtgCustomers.Rows[i].Cells[8].Value != null && "true".Equals(dtgCustomers.Rows[i].Cells[8].Value.ToString().ToLower()))
                {
                    id = int.Parse(dtgCustomers.Rows[i].Cells[0].Value.ToString());
                    ListId.Add(id);
                }
            }
            if(ListId.Count >0)
            {
                Confirm f = new Confirm("Bạn muốn cho nghỉ tập tất cả các học viên này.");
                f.ShowDialog();
                if (f.IsAccept)
                {
                    CustomerDao dao = new CustomerDao();
                    if (dao.deteteCustomer(ListId))
                    {
                        Result r = new Result("Cho nghỉ tập thành công.");
                        r.ShowDialog();
                        r.Dispose();
                    }
                    string name = txtName.Text.Trim();
                    string active = "A";
                    bool fifo = false;
                    if (cbxInactive.Checked)
                    {
                        active = null;
                    }
                    if (cbxFifo.Checked)
                    {
                        fifo = true;
                    }
                    dtgCustomers.Rows.Clear();
                    rowNumber = 0;
                    init(name, active, fifo);
                }
            }
            else
            {
                Error er = new Error("Vui lòng chọn học viên mà bạn muốn cho nghỉ tập");
                er.ShowDialog();
                er.Dispose();
            }
        }

        private void CustomerList_Shown(object sender, EventArgs e)
        {
            
        }

        private void btnSales_Click(object sender, EventArgs e)
        {
            FSale f = new FSale();
            f.ShowDialog();
            f.Dispose();
        }

        private void btnWarning_Click(object sender, EventArgs e)
        {
            WarningList wr = new WarningList();
            wr.ShowDialog();
            wr.Dispose();
        }
    }
}
